package com.mhuang.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mhuang.common.Closeable;
import com.mhuang.common.client.AbstractNettyClient;
import com.mhuang.common.client.MyNettyClient;
import com.mhuang.common.handler.ClientChannelInitializerHandler;
import com.mhuang.vo.HeaderStruct;
import com.mhuang.vo.P0002;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 
 * @Description netty 客户端 Demo
 * @author mHuang
 * @date 2015年7月16日 下午2:55:36 
 * @version V1.0.0
 */
public class NettyClient extends AbstractNettyClient implements Closeable{
	
	private static final long serialVersionUID = 1L;

	
	public static  Channel channel = null;
	
	@Override
	public void connect(String host,int port) {
		//config thread pool
        EventLoopGroup group=new NioEventLoopGroup();
        try{
            //config client aotu property
            Bootstrap b=new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
            .handler(new ClientChannelInitializerHandler());
            // Start the client.
            ChannelFuture f = b.connect(host,port).sync();
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
            
        } catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
            group.shutdownGracefully();
        }
	}

	@Override
	public void connect() {
		connect(host,port);
	}
	
	public static void main(String[] args){
		MyNettyClient nettyClient = new NettyClient();
		nettyClient.connect("127.0.0.1", 8181);
	}

	@Override
	public void close() {
		NettyClient.channel.close();
	}
	
	class ClientTask implements Runnable{
		/**
		 * 日志对象
		 */
		protected Logger logger = LoggerFactory.getLogger(ClientTask.class);
		public void run() {
			try {
				while (true) {
					if (null != NettyClient.channel) {
						if (NettyClient.channel.isActive() && NettyClient.channel.isWritable()) {
//							NettyClient.channel.writeAndFlush("我是客户端发的消息.....");
						} else { //重连
							logger.error("客户端重连....");
							NettyClient.channel.close();
							new NettyClient().connect();
						}
					}
					Thread.sleep(10000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
